package main

import (
	mgo "gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

type DBOperator struct {
	dbName  string
	session *mgo.Session
}

const CollectionGPS string = "gps"

func NewDBOperator(url, dbName, userName, password string) (*DBOperator, error) {
	zLog(nil, "数据库连接::", url, " 开始")
	session, err := mgo.Dial(url)
	if err != nil {
		zLog(nil, "数据库连接失败::", err.Error())
		return nil, err
	}
	if userName != "" && password != "" {
		err = session.Login(&mgo.Credential{
			Username: userName,
			Password: password,
		})
		if err != nil {
			zLog(nil, "数据库登录失败::", err.Error())
			return nil, err
		}
	}
	session.SetPoolLimit(200)
	dbo := DBOperator{dbName: dbName, session: session}
	return &dbo, nil
}

func (p *DBOperator) Save(lat, lng float64, address string, fixed int, language string) {
	s := p.session.Copy()
	defer s.Close()

	c := s.DB(p.dbName).C(CollectionGPS)
	c.Upsert(bson.M{"lat": lat, "lng": lng, "fixed": fixed, "lang": language}, bson.M{"$set": bson.M{"add": address}})
}

type AddressT struct {
	Address string `bson:"add"`
}

func (p *DBOperator) Search(lat, lng float64, fixed int, language string) string {
	s := p.session.Copy()
	defer s.Close()

	c := s.DB(p.dbName).C(CollectionGPS)
	var add AddressT

	err := c.Find(bson.M{"lat": lat, "lng": lng, "fixed": fixed, "lang": language}).Select(bson.M{"_id": 0, "add": 1}).Limit(1).One(&add)
	if err != nil {
		return ""
	}
	return add.Address
}
